<template>
    <div>
        <!-- 条件查询 -->
        <el-card>

            <!-- 动态按钮 -->
            <el-button type="default" size="default" v-for="item in buttonList" :key="item.PId"
                @click="dynamicButtonClick(item.PId)">{{
                item.PName
            }}</el-button>

            <!-- 添加弹出层 -->
            <el-dialog title="员工添加" v-model="addVisiable" width="50%">
                <el-form :model="addForm" ref="ruleFormRef" :rules="addRules" label-width="100px" :inline="false"
                    status-icon style="width:500px;margin:0 auto">
                    <el-form-item label="登录账号" prop="empName">
                        <el-input v-model="addForm.empName"></el-input>
                    </el-form-item>
                    <el-form-item label="登录密码" prop="empPwd">
                        <el-input v-model="addForm.empPwd" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="tel">
                        <el-input v-model="addForm.tel"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>

                    <el-form-item label="性别">
                        <el-radio-group v-model='addForm.gender'>
                            <el-radio :label="true">男</el-radio>
                            <el-radio :label="false">女</el-radio>

                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="角色" prop="roleId">
                        <el-select v-model="addForm.roleId" placeholder="请选择角色">
                            <el-option v-for="item in roleList.value" :key="item.RoleId" :label="item.RoleName"
                                :value="item.RoleId">
                            </el-option>
                        </el-select>

                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realName">
                        <el-input v-model="addForm.realName"></el-input>
                    </el-form-item>
                    <el-form-item label="门店" prop="storeId">
                        <el-select v-model="addForm.storeId" placeholder="请选择门店" clearable filterable
                            :disabled="!store.getUserInfo().IsTenant">
                            <el-option v-for="item in storeList.values" :key="item.StoreId" :label="item.StoreName"
                                :value="item.StoreId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="empAdd(ruleFormRef)">添加</el-button>
                        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

            <!-- 角色权限修改弹出层 -->
            <el-dialog title="角色权限" v-model="updPermissionVisiable" width="35%">
                <div>
                    <el-radio-group v-model="empRole">
                        <el-radio v-for="item in roleList.value" :key="item.RoleId" :label="item.RoleId"
                            style="float: left;width:24%">{{
                item.RoleName
            }}</el-radio>
                    </el-radio-group>
                </div>
                <div style="text-align:center;margin-top:20px">
                    <el-button type="primary" @click="updEmpPermission()">保存</el-button>
                </div>
            </el-dialog>

            <span style="float:right">
                <el-select v-model="condition.flag" clearable filterable class="group">
                    <el-option label="员工姓名" :value="0" />

                    <el-option label="手机号" :value="1" />

                </el-select>
                <el-input v-model="condition.search" class="group"></el-input>
                <el-button class="group" @click="handleCurrentChange(1)" type="primary">查询</el-button>

            </span>

        </el-card>
        <!-- 列表显示 -->


        <el-card>
            <el-table :data="empList" stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" align="center">
                </el-table-column>
                <el-table-column prop="RealName" label="员工姓名" align="center">
                </el-table-column>

                <el-table-column prop="Tel" label="手机号" align="center">
                </el-table-column>
                <el-table-column prop="Email" label="邮箱" align="center">
                </el-table-column>
                <el-table-column prop="Gender" label="性别" align="center">
                    <template v-slot="scope">
                        {{ scope.row.Gender ? "男" : "女" }}
                    </template>
                </el-table-column>
                <el-table-column prop="StoreName" label="门店" align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template v-slot="scope">
                        <el-link type="warning" @click="updVisiable = true; getEmpByEmpId(scope.row.EmpId)">编辑</el-link>
                        <!-- 修改弹出层 -->
                        <el-dialog title="员工信息修改" v-model="updVisiable" width="50%">
                            <el-form :model="updForm" ref="ruleFormRef" :rules="addRules" label-width="100px"
                                :inline="false" status-icon style="width:500px;margin:0 auto">
                                <el-form-item label="登录账号" prop="empName">
                                    <el-input v-model="updForm.empName"></el-input>
                                </el-form-item>
                                <el-form-item label="登录密码" prop="empPwd">
                                    <el-input v-model="updForm.empPwd" show-password disabled></el-input>
                                </el-form-item>
                                <el-form-item label="手机号码" prop="tel">
                                    <el-input v-model="updForm.tel"></el-input>
                                </el-form-item>
                                <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="updForm.email"></el-input>
                                </el-form-item>
                                <el-form-item label="门店" prop="storeId">
                                    <el-select v-model="updForm.storeId" placeholder="请选择门店" clearable filterable>
                                        <el-option v-for="item in storeList.values" :key="item.StoreId"
                                            :label="item.StoreName" :value="item.StoreId">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="性别">
                                    <el-radio-group v-model='updForm.gender'>
                                        <el-radio :label="true">男</el-radio>
                                        <el-radio :label="false">女</el-radio>

                                    </el-radio-group>
                                </el-form-item>

                                <el-form-item label="真实姓名" prop="realName">
                                    <el-input v-model="updForm.realName"></el-input>
                                </el-form-item>

                                <el-form-item>
                                    <el-button type="primary" @click="empUpd(ruleFormRef)">修改</el-button>
                                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                                </el-form-item>
                            </el-form>
                        </el-dialog>

                    </template>
                </el-table-column>

            </el-table>

        </el-card>
        <el-card>
            <!-- 分页 -->
            <table style="margin: 5px auto;">
                <tbody>
                    <tr>
                        <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                                :page-sizes="[1, 2, 3, 10]" layout="total, slot,sizes" :total="pager.totalCount"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                                next-text="下一页">
                                <span class="el-pagination__total is-first">&nbsp;共计{{ pager.pageCount }}页,当前{{
                pager.pageIndex
            }}/{{ pager.pageCount }}页</span>
                            </el-pagination>
                        </td>
                        <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                                :page-sizes="[1, 2, 3, 10]" layout="slot, prev, pager" :total="pager.totalCount"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                                next-text="下一页">
                                <button @click="handleCurrentChange(1)" :disabled="pager.pageIndex == 1"
                                    class="btn-prev">首页</button>
                            </el-pagination></td>
                        <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                                :page-sizes="[1, 2, 3, 10]" layout="slot, next, jumper" :total="pager.totalCount"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                                next-text="下一页">
                                <button @click="handleCurrentChange(pager.pageCount)"
                                    :disabled="pager.pageIndex == pager.pageCount" class="next-prev">尾页</button>
                            </el-pagination></td>
                    </tr>
                </tbody>
            </table>
        </el-card>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { loginStore } from "@/stores/login"
import type { FormInstance, FormRules } from 'element-plus'

import { ElMessage } from "element-plus"

import axios from 'axios';
import { baseURL_dev } from '@/config/baseURL'

const baseURL = baseURL_dev

axios.defaults.baseURL = baseURL;

const Route = useRoute()
const store = loginStore();

const ruleFormRef = ref<FormInstance>()
//表单自定义验证
const checkEmpName = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('登录账号不能为空'))
    }
    axios.get("Employee/EmpNameUnique?empName=" + value).then(res => {
        if (!res.data.Data) {
            return callback(new Error('该账号已存在'));
        }
        return callback();
    })



}
const checkTel = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('手机号码不能为空'))
    }
    axios.get("Employee/TelUnique?tel=" + value).then(res => {
        if (!res.data.Data) {
            return callback(new Error('该手机号码已被注册'));
        }
        return callback();
    })
}
const condition = reactive({
    flag: 0,
    search: "",
})
const pager = reactive({
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
    pageCount: 0,
})
const empList = ref([])

//获取员工列表
function getEmpList() {
    let storeId = store.getUserInfo().StoreId;
    if (typeof (storeId) != 'number') {
        storeId = 0
    }
    console.log(typeof (storeId));
    axios.get("Employee/ConditionQueryGetEmployees", {
        params: {
            storeId: storeId,
            flag: condition.flag,
            search: condition.search,
            pageIndex: pager.pageIndex,
            pageSize: pager.pageSize
        }
    }).then(res => {
        empList.value = res.data.Data;
        pager.pageCount = res.data.PageCount;
        pager.totalCount = res.data.TotalCount;
    })
}

function handleSizeChange(size) {
    pager.pageSize = size;
    getEmpList();
}
function handleCurrentChange(index) {
    pager.pageIndex = index;
    getEmpList();
}
const multipleSelection = ref([])
//批量删除
function handleSelectionChange(val) {
    multipleSelection.value = val;
}
//文件导出为Excel
function exportExcel() {
    axios({
        method: "post",
        url: "Employee/ExportExcel",
        data: {},
        //设置请求头的 Content-Type 为 “application/json;charset=UTF-8”
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
        },
        //设置响应的 responseType 为 “blob”，表示返回的数据是二进制数据
        responseType: "blob",
    })
        .then((res) => {
            console.log(res, "res");
            //创建一个 Blob 对象来存储数据
            const blob = new Blob([res.data]);
            //使用 URL.createObjectURL() 方法生成一个 URL，指向这个 Blob 对象
            let url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            //创建一个<a>标签，设置其href属性为这个URL，download属性为要下载的文件名
            link.download = "用户数据导出.xlsx";
            //触发<a>标签的点击事件
            link.click();
            //URL.revokeObjectURL()方法释放这个URL对象
            URL.revokeObjectURL(url);
        })
        .catch((err) => {
            ElMessage({
                message: err.message,
                type: "error",
            });
        });
}
const buttonList = ref([])
//根据路径获取按钮权限
function getButtonPermissionsByPath() {
    let empId = '';
    if (store.getUserInfo().IsTenant) {
        empId = store.getUserInfo().TenantId + 'admin'
    }
    else {
        empId = store.getUserInfo().UId
    }
    axios.get("Permission/GetButtonPermissionsByPath", {
        params: {
            empId: empId,
            path: Route.fullPath
        }
    }).then(res => {
        buttonList.value = res.data.Data;
    })
}
function dynamicButtonClick(pid: string) {
    switch (pid) {
        //批量导出
        case "M2001001": exportExcel(); break;
        //员工添加
        case "M2001002": addVisiable.value = true; break;
        //权限修改
        case "M2001003":
            if (multipleSelection.value.length == 0) {
                ElMessage.error("至少选择一项");
                return;
            }
            if (multipleSelection.value.length > 1) {
                ElMessage.error("只能选择一项");
                return;
            }
            getEmpRole();
            updPermissionVisiable.value = true; break;
    }
}
//角色列表
const roleList = reactive({
    RoleId: 0,
    RoleName: "",
})
function getRoleList() {
    axios.get("Role/GetAllRoleList").then(res => {
        roleList.value = res.data.Data;
        console.log(roleList)
    })
}
const empRole = ref('')
//根据用户编号获取用户角色
function getEmpRole() {
    let empId = multipleSelection.value[0].EmpId;
    axios.get("Employee/GetEmpRoleId?empId=" + empId).then(res => {
        if (res.data.Code == 200) {
            empRole.value = res.data.Data;
        }
    })

}
//修改员工角色
function updEmpPermission() {
    let empId = multipleSelection.value[0].EmpId;
    axios.post(`EmpRole/EmpRoleUpd?empId=${empId}&roleId=${empRole.value}`).then(res => {
        if (res.data.Code == 200) {
            ElMessage.success("修改成功");
            getEmpList();
            updPermissionVisiable.value = false;
            empRole.value = '';
        }
        else {
            ElMessage.error("修改失败");
        }
    })
}
//门店列表
const storeList = reactive({
    StoreId: 0,
    StoreName: "",
})
//获取门店列表
function getStoreList() {
    axios.get('Store/GetStoreListByTenantIdUseForEmpAdd').then(res => {
        storeList.values = res.data.Data;
        //console.log(storeList.values)
    })
}
//添加弹出框
const addVisiable = ref(false)
const addForm = reactive({
    "empId": "",
    "empName": "ceshi004",
    "empPwd": "123",
    "tel": "13103751806",
    "email": "ceshi004@qq.com",
    "gender": true,
    //"entryTime": "",
    //"empStatus": 1,
    "storeId": store.getUserInfo().StoreId,
    "realName": "测试员工004",
    "roleId": ''
})

const addRules = reactive<FormRules<typeof addForm>>({

    "empName": [{ validator: checkEmpName, trigger: 'blur' }],
    "empPwd": [{ required: true, message: "登录密码不能为空", trigger: 'blur' }],
    "tel": [{ validator: checkTel, trigger: 'blur' }],
    "email": [{ required: true, message: "邮箱不能为空", trigger: 'blur' }],
    "storeId": [{
        required: true,
        message: '请选择门店',
        trigger: 'change',
    },],
    "realName": [{ required: true, message: "真实姓名不能为空", trigger: 'blur' }],
    "roleId": [{
        required: true,
        message: '请选择角色',
        trigger: 'change',
    }],

})
//添加员工
const empAdd = (formEl: FormInstance | undefined) => {
    console.log(new Date().toLocaleDateString())
    console.log(new Date().toLocaleTimeString())
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            axios.post("Employee/EmployeeAdd", addForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage({
                        message: '添加成功',
                        type: 'success'
                    })
                    getEmpList();
                    addVisiable.value = false;
                }
                else {
                    ElMessage({
                        message: '添加失败',
                        type: 'error'
                    })
                }
            })
        } else {
            console.log('error submit!')
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
//修改权限弹出框
const updPermissionVisiable = ref(false)
const updForm = reactive({
    "empId": "",
    "empName": "",
    "empPwd": "",
    "tel": "",
    "email": "",
    "gender": true,
    //"entryTime": "",
    "empStatus": 1,
    "storeId": 0,
    "realName": "",

})
//修改员工信息弹出框
const updVisiable = ref(false)

//员工信息编辑
function getEmpByEmpId(empId: string) {
    axios.get("Employee/GetEmpByEmpId?empId=" + empId).then(res => {
        updForm.empId = empId;
        updForm.empName = res.data.Data.EmpName;
        updForm.empPwd = res.data.Data.EmpPwd;
        updForm.tel = res.data.Data.Tel;
        updForm.email = res.data.Data.Email;
        updForm.gender = res.data.Data.Gender;
        //updForm.entryTime = res.data.Data.EntryTime;
        updForm.empStatus = res.data.Data.EmpStatus;
        updForm.storeId = res.data.Data.StoreId;
        updForm.realName = res.data.Data.RealName;
    })
}

//员工信息修改
const empUpd = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            axios.post("Employee/UpdEmpInfo", updForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage({
                        message: '修改成功',
                        type: 'success'
                    })
                    getEmpList();
                    updVisiable.value = false;
                }
                else {
                    ElMessage({
                        message: res.data.Msg,
                        type: 'error'
                    })
                }
            })
        } else {
            console.log('error submit!')
        }
    })
}

onMounted(() => {
    getButtonPermissionsByPath();
    getRoleList();
    getStoreList();
    getEmpList()
})  
</script>
<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.group {
    width: 100px
}

.el-card {
    margin-bottom: 20px;
}
</style>